<!-- build time:Tue Dec 17 2019 19:26:43 GMT+0800 (GMT+08:00) --><!doctype html><html class="theme-next mist" lang="zh-Hans"><head><meta name="generator" content="Hexo 3.8.0"><meta name="google-site-verification" content="7Tau9WyVgxnsEY9oYedu9g0U6_8akOX3wiKbaYcrg9A"><meta name="baidu-site-verification" content="EVwLiaxdxX"><link href="/css/xps13.css" rel="stylesheet" type="text/css"><link href="/css/message.css" rel="stylesheet" type="text/css"><script type="text/javascript" src="/js/jquery-1.11.3.min.js"></script><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css"><link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css"><meta name="keywords" content="Spring,Security,Spring Security,"><link rel="alternate" href="/atom.xml" title="MrBird" type="application/atom+xml"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1"><meta name="description" content="在Spring Security添加图形验证码一节中，我们已经实现了基于Spring Boot + Spring Security的账号密码登录，并集成了图形验证码功能。时下另一种非常常见的网站登录方式为手机短信验证码登录，但Spring Security默认只提供了账号密码的登录认证逻辑，所以要实现手机短信验证码登录认证功能，我们需要模仿Spring Security账号密码登录逻辑代码来实现一"><meta name="keywords" content="Spring,Security,Spring Security"><meta property="og:type" content="article"><meta property="og:title" content="Spring Security短信验证码登录"><meta property="og:url" content="http://mrbird.cc/Spring-Security-SmsCode.html"><meta property="og:site_name" content="MrBird"><meta property="og:description" content="在Spring Security添加图形验证码一节中，我们已经实现了基于Spring Boot + Spring Security的账号密码登录，并集成了图形验证码功能。时下另一种非常常见的网站登录方式为手机短信验证码登录，但Spring Security默认只提供了账号密码的登录认证逻辑，所以要实现手机短信验证码登录认证功能，我们需要模仿Spring Security账号密码登录逻辑代码来实现一"><meta property="og:locale" content="zh-Hans"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180729204953.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180730220603.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180730224103.png"><meta property="og:image" content="http://mrbird.cc/img/QQ截图20180731230532.png"><meta property="og:updated_time" content="2019-10-28T12:14:46.284Z"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="Spring Security短信验证码登录"><meta name="twitter:description" content="在Spring Security添加图形验证码一节中，我们已经实现了基于Spring Boot + Spring Security的账号密码登录，并集成了图形验证码功能。时下另一种非常常见的网站登录方式为手机短信验证码登录，但Spring Security默认只提供了账号密码的登录认证逻辑，所以要实现手机短信验证码登录认证功能，我们需要模仿Spring Security账号密码登录逻辑代码来实现一"><meta name="twitter:image" content="http://mrbird.cc/img/QQ截图20180729204953.png"><script type="text/javascript" id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Mist",sidebar:{position:"left",display:"always",offset:12,offset_float:0,b2t:!1,scrollpercent:!1},fancybox:!1,motion:!1}</script><title>Spring Security短信验证码登录 | MrBird</title></head><body ondragstart="return!1" class="animsition" lang="zh-Hans" style="overflow-x:hidden;padding-right:280px"><script type="text/javascript" src="/js/mo.min.js"></script><style>@media (min-width:768px) and (max-width:991px){body .header-innerr{width:700px!important}}.header-innerr{margin:0 auto;padding:100px 0 70px;width:880px}@media (min-width:1600px){.container .header-innerr{width:1200px}}.header-innerr{position:relative}.header-innerr{padding:20px 0 0}.header-innerr:after,.header-innerr:before{content:" ";display:table}.header-innerr:after{clear:both}@media (max-width:767px){.header-innerr{width:auto;padding:10px;margin-bottom:-20px}}</style><div class="container sidebar-position-left page-post-detail"><div class="headband"></div><header id="header" class="header"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><link href="https://fonts.font.im/css?family=Merienda" rel="stylesheet"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title" style="font-family:Merienda;font-size:1.3rem">MrBird</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle"></p></div><div class="site-nav-toggle"><button><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section">HOME</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section">ARCHIVES</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section">TAGS</a></li><li class="menu-item menu-item-friends"><a href="/friends/" rel="section">FRIENDS</a></li><div class="sidebar-toggle" style="display:none"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="Search" spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div><div class="header-innerr"><div class="note info" style="margin:0;letter-spacing:.15px">🐤手把手教你搭建<strong>Spring Cloud微服务权限系统</strong>（从零到部署）：<a style="color:#40dab2;font-weight:600" href="https://www.kancloud.cn/mrbird/spring-cloud" target="_blank">https://www.kancloud.cn/mrbird/spring-cloud</a></div></div></header><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div id="posts" class="posts-expand"><article class="post post-type-normal" itemscope itemtype="http://schema.org/Article"><link itemprop="mainEntityOfPage" href="http://mrbird.cc/Spring-Security-SmsCode.html"><span hidden itemprop="author" itemscope itemtype="http://schema.org/Person"><meta itemprop="name" content="MrBird"><meta itemprop="description" content=""><meta itemprop="image" content="/images/blogImage.jpg"></span><span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization"><meta itemprop="name" content="MrBird"></span><header class="post-header"><h1 class="post-title" itemprop="name headline">Spring Security短信验证码登录</h1><div class="post-meta"><span class="post-time"><span class="post-meta-item-icon"><i class="fa fa-calendar-o"></i> </span><span class="post-meta-item-text">Posted on</span> <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-05-11T17:06:02+08:00">2018-05-11 </time></span><span></span> <span class="post-meta-divider">|</span> <span class="page-pv"><i class="fa fa-laptop"></i>&nbsp;&nbsp;Visit count <span class="busuanzi-value" id="busuanzi_value_page_pv"></span></span></div></header><div class="post-body" itemprop="articleBody"><p>在<a href="/Spring-Security-ValidateCode.html">Spring Security添加图形验证码</a>一节中，我们已经实现了基于Spring Boot + Spring Security的账号密码登录，并集成了图形验证码功能。时下另一种非常常见的网站登录方式为手机短信验证码登录，但Spring Security默认只提供了账号密码的登录认证逻辑，所以要实现手机短信验证码登录认证功能，我们需要模仿Spring Security账号密码登录逻辑代码来实现一套自己的认证逻辑。<a id="more"></a></p><h2 id="短信验证码生成"><a href="#短信验证码生成" class="headerlink" title="短信验证码生成"></a>短信验证码生成</h2><p>我们在上一节<a href="/Spring-Security-ValidateCode.html">Spring Security添加图形验证码</a>的基础上来集成短信验证码登录的功能。</p><p>和图形验证码类似，我们先定义一个短信验证码对象SmsCode：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsCode</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String code;</span><br><span class="line">    <span class="keyword">private</span> LocalDateTime expireTime;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsCode</span><span class="params">(String code, <span class="keyword">int</span> expireIn)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.code = code;</span><br><span class="line">        <span class="keyword">this</span>.expireTime = LocalDateTime.now().plusSeconds(expireIn);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsCode</span><span class="params">(String code, LocalDateTime expireTime)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.code = code;</span><br><span class="line">        <span class="keyword">this</span>.expireTime = expireTime;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">boolean</span> <span class="title">isExpire</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> LocalDateTime.now().isAfter(expireTime);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// get,set略</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>SmsCode对象包含了两个属性：code验证码和expireTime过期时间。isExpire方法用于判断短信验证码是否已过期。</p><p>接着在ValidateCodeController中加入生成短信验证码相关请求对应的方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ValidateController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">static</span> String SESSION_KEY_SMS_CODE = <span class="string">"SESSION_KEY_SMS_CODE"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> SessionStrategy sessionStrategy = <span class="keyword">new</span> HttpSessionSessionStrategy();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/code/sms"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">createSmsCode</span><span class="params">(HttpServletRequest request, HttpServletResponse response, String mobile)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        SmsCode smsCode = createSMSCode();</span><br><span class="line">        sessionStrategy.setAttribute(<span class="keyword">new</span> ServletWebRequest(request), SESSION_KEY_SMS_CODE + mobile, smsCode);</span><br><span class="line">        <span class="comment">// 输出验证码到控制台代替短信发送服务</span></span><br><span class="line">        System.out.println(<span class="string">"您的登录验证码为："</span> + smsCode.getCode() + <span class="string">"，有效时间为60秒"</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> SmsCode <span class="title">createSMSCode</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        String code = RandomStringUtils.randomNumeric(<span class="number">6</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SmsCode(code, <span class="number">60</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>这里我们使用<code>createSMSCode</code>方法生成了一个6位的纯数字随机数，有效时间为60秒。然后通过<code>SessionStrategy</code>对象的<code>setAttribute</code>方法将短信验证码保存到了Session中，对应的key为<code>SESSION_KEY_SMS_CODE</code>。</p><p>至此，短信验证码生成模块编写完毕，下面开始改造登录页面。</p><h2 id="改造登录页"><a href="#改造登录页" class="headerlink" title="改造登录页"></a>改造登录页</h2><p>我们在登录页面中加入一个与手机短信验证码认证相关的Form表单：</p><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">form</span> <span class="attr">class</span>=<span class="string">"login-page"</span> <span class="attr">action</span>=<span class="string">"/login/mobile"</span> <span class="attr">method</span>=<span class="string">"post"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"form"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">h3</span>&gt;</span>短信验证码登录<span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">placeholder</span>=<span class="string">"手机号"</span> <span class="attr">name</span>=<span class="string">"mobile"</span> <span class="attr">value</span>=<span class="string">"17777777777"</span> <span class="attr">required</span>=<span class="string">"required"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">span</span> <span class="attr">style</span>=<span class="string">"display: inline"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"text"</span> <span class="attr">name</span>=<span class="string">"smsCode"</span> <span class="attr">placeholder</span>=<span class="string">"短信验证码"</span> <span class="attr">style</span>=<span class="string">"width: 50%;"</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"/code/sms?mobile=17777777777"</span>&gt;</span>发送验证码<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">span</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">"submit"</span>&gt;</span>登录<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">form</span>&gt;</span></span><br></pre></td></tr></table></figure><p></p><p>其中a标签的<code>href</code>属性值对应我们的短信验证码生成方法的请求URL。Form的action对应处理短信验证码登录方法的请求URL，这个方法下面在进行具体实现。同时，我们需要在Spring Security中配置<code>/code/sms</code>路径免验证：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">    http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) <span class="comment">// 添加验证码校验过滤器</span></span><br><span class="line">            .formLogin() <span class="comment">// 表单登录</span></span><br><span class="line">                <span class="comment">// http.httpBasic() // HTTP Basic</span></span><br><span class="line">                .loginPage(<span class="string">"/authentication/require"</span>) <span class="comment">// 登录跳转 URL</span></span><br><span class="line">                .loginProcessingUrl(<span class="string">"/login"</span>) <span class="comment">// 处理表单登录 URL</span></span><br><span class="line">                .successHandler(authenticationSucessHandler) <span class="comment">// 处理登录成功</span></span><br><span class="line">                .failureHandler(authenticationFailureHandler) <span class="comment">// 处理登录失败</span></span><br><span class="line">            .and()</span><br><span class="line">                .authorizeRequests() <span class="comment">// 授权配置</span></span><br><span class="line">                .antMatchers(<span class="string">"/authentication/require"</span>,</span><br><span class="line">                        <span class="string">"/login.html"</span>, <span class="string">"/code/image"</span>,<span class="string">"/code/sms"</span>).permitAll() <span class="comment">// 无需认证的请求路径</span></span><br><span class="line">                .anyRequest()  <span class="comment">// 所有请求</span></span><br><span class="line">                .authenticated() <span class="comment">// 都需要认证</span></span><br><span class="line">            .and()</span><br><span class="line">                .csrf().disable();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>重启项目，访问<a href="http://localhost:8080/login.html" target="_blank" rel="noopener">http://localhost:8080/login.html</a>：</p><p><img src="img/QQ截图20180729204953.png" alt="QQ截图20180729204953.png"></p><p>点击发送验证码，控制台输出如下：</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">您的登录验证码为：693583，有效时间为60秒</span><br></pre></td></tr></table></figure><p></p><p>接下来开始实现使用短信验证码登录认证逻辑。</p><h2 id="添加短信验证码认证"><a href="#添加短信验证码认证" class="headerlink" title="添加短信验证码认证"></a>添加短信验证码认证</h2><p>在Spring Security中，使用用户名密码认证的过程大致如下图所示：</p><p><img src="img/QQ截图20180730220603.png" alt="QQ截图20180730220603.png"></p><p>Spring Security使用<code>UsernamePasswordAuthenticationFilter</code>过滤器来拦截用户名密码认证请求，将用户名和密码封装成一个<code>UsernamePasswordToken</code>对象交给<code>AuthenticationManager</code>处理。<code>AuthenticationManager</code>将挑出一个支持处理该类型Token的<code>AuthenticationProvider</code>（这里为<code>DaoAuthenticationProvider</code>，<code>AuthenticationProvider</code>的其中一个实现类）来进行认证，认证过程中<code>DaoAuthenticationProvider</code>将调用<code>UserDetailService</code>的<code>loadUserByUsername</code>方法来处理认证，如果认证通过（即<code>UsernamePasswordToken</code>中的用户名和密码相符）则返回一个<code>UserDetails</code>类型对象，并将认证信息保存到Session中，认证后我们便可以通过<code>Authentication</code>对象获取到认证的信息了。</p><p>由于Spring Security并没用提供短信验证码认证的流程，所以我们需要仿照上面这个流程来实现：</p><p><img src="img/QQ截图20180730224103.png" alt="QQ截图20180730224103.png"></p><p>在这个流程中，我们自定义了一个名为<code>SmsAuthenticationFitler</code>的过滤器来拦截短信验证码登录请求，并将手机号码封装到一个叫<code>SmsAuthenticationToken</code>的对象中。在Spring Security中，认证处理都需要通过<code>AuthenticationManager</code>来代理，所以这里我们依旧将<code>SmsAuthenticationToken</code>交由<code>AuthenticationManager</code>处理。接着我们需要定义一个支持处理<code>SmsAuthenticationToken</code>对象的<code>SmsAuthenticationProvider</code>，<code>SmsAuthenticationProvider</code>调用<code>UserDetailService</code>的<code>loadUserByUsername</code>方法来处理认证。与用户名密码认证不一样的是，这里是通过<code>SmsAuthenticationToken</code>中的手机号去数据库中查询是否有与之对应的用户，如果有，则将该用户信息封装到<code>UserDetails</code>对象中返回并将认证后的信息保存到<code>Authentication</code>对象中。</p><p>为了实现这个流程，我们需要定义<code>SmsAuthenticationFitler</code>、<code>SmsAuthenticationToken</code>和<code>SmsAuthenticationProvider</code>，并将这些组建组合起来添加到Spring Security中。下面我们来逐步实现这个过程。</p><h3 id="定义SmsAuthenticationToken"><a href="#定义SmsAuthenticationToken" class="headerlink" title="定义SmsAuthenticationToken"></a>定义SmsAuthenticationToken</h3><p>查看<code>UsernamePasswordAuthenticationToken</code>的源码，将其复制出来重命名为<code>SmsAuthenticationToken</code>，并稍作修改，修改后的代码如下所示：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsAuthenticationToken</span> <span class="keyword">extends</span> <span class="title">AbstractAuthenticationToken</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = SpringSecurityCoreVersion.SERIAL_VERSION_UID;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Object principal;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsAuthenticationToken</span><span class="params">(String mobile)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="keyword">null</span>);</span><br><span class="line">        <span class="keyword">this</span>.principal = mobile;</span><br><span class="line">        setAuthenticated(<span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsAuthenticationToken</span><span class="params">(Object principal, Collection&lt;? extends GrantedAuthority&gt; authorities)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(authorities);</span><br><span class="line">        <span class="keyword">this</span>.principal = principal;</span><br><span class="line">        <span class="keyword">super</span>.setAuthenticated(<span class="keyword">true</span>); <span class="comment">// must use super, as we override</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getCredentials</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">getPrincipal</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.principal;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setAuthenticated</span><span class="params">(<span class="keyword">boolean</span> isAuthenticated)</span> <span class="keyword">throws</span> IllegalArgumentException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (isAuthenticated) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(</span><br><span class="line">                    <span class="string">"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">super</span>.setAuthenticated(<span class="keyword">false</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">eraseCredentials</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.eraseCredentials();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p><code>SmsAuthenticationToken</code>包含一个<code>principal</code>属性，从它的两个构造函数可以看出，在认证之前<code>principal</code>存的是手机号，认证之后存的是用户信息。<code>UsernamePasswordAuthenticationToken</code>原来还包含一个<code>credentials</code>属性用于存放密码，这里不需要就去掉了。</p><h3 id="定义SmsAuthenticationFilter"><a href="#定义SmsAuthenticationFilter" class="headerlink" title="定义SmsAuthenticationFilter"></a>定义SmsAuthenticationFilter</h3><p>定义完<code>SmsAuthenticationToken</code>后，我们接着定义用于处理短信验证码登录请求的过滤器<code>SmsAuthenticationFilter</code>，同样的复制<code>UsernamePasswordAuthenticationFilter</code>源码并稍作修改：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsAuthenticationFilter</span> <span class="keyword">extends</span> <span class="title">AbstractAuthenticationProcessingFilter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String MOBILE_KEY = <span class="string">"mobile"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> String mobileParameter = MOBILE_KEY;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">boolean</span> postOnly = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SmsAuthenticationFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(<span class="keyword">new</span> AntPathRequestMatcher(<span class="string">"/login/mobile"</span>, <span class="string">"POST"</span>));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Authentication <span class="title">attemptAuthentication</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">                                                HttpServletResponse response)</span> <span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (postOnly &amp;&amp; !request.getMethod().equals(<span class="string">"POST"</span>)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> AuthenticationServiceException(</span><br><span class="line">                    <span class="string">"Authentication method not supported: "</span> + request.getMethod());</span><br><span class="line">        &#125;</span><br><span class="line">        String mobile = obtainMobile(request);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (mobile == <span class="keyword">null</span>) &#123;</span><br><span class="line">            mobile = <span class="string">""</span>;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        mobile = mobile.trim();</span><br><span class="line"></span><br><span class="line">        SmsAuthenticationToken authRequest = <span class="keyword">new</span> SmsAuthenticationToken(mobile);</span><br><span class="line"></span><br><span class="line">        setDetails(request, authRequest);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.getAuthenticationManager().authenticate(authRequest);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> String <span class="title">obtainMobile</span><span class="params">(HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> request.getParameter(mobileParameter);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">setDetails</span><span class="params">(HttpServletRequest request,</span></span></span><br><span class="line"><span class="function"><span class="params">                              SmsAuthenticationToken authRequest)</span> </span>&#123;</span><br><span class="line">        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMobileParameter</span><span class="params">(String mobileParameter)</span> </span>&#123;</span><br><span class="line">        Assert.hasText(mobileParameter, <span class="string">"mobile parameter must not be empty or null"</span>);</span><br><span class="line">        <span class="keyword">this</span>.mobileParameter = mobileParameter;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setPostOnly</span><span class="params">(<span class="keyword">boolean</span> postOnly)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.postOnly = postOnly;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">final</span> String <span class="title">getMobileParameter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mobileParameter;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>构造函数中指定了当请求为<code>/login/mobile</code>，请求方法为<strong>POST</strong>的时候该过滤器生效。<code>mobileParameter</code>属性值为mobile，对应登录页面手机号输入框的name属性。<code>attemptAuthentication</code>方法从请求中获取到mobile参数值，并调用<code>SmsAuthenticationToken</code>的<code>SmsAuthenticationToken(String mobile)</code>构造方法创建了一个<code>SmsAuthenticationToken</code>。下一步就如流程图中所示的那样，<code>SmsAuthenticationFilter</code>将<code>SmsAuthenticationToken</code>交给<code>AuthenticationManager</code>处理。</p><h3 id="定义SmsAuthenticationProvider"><a href="#定义SmsAuthenticationProvider" class="headerlink" title="定义SmsAuthenticationProvider"></a>定义SmsAuthenticationProvider</h3><p>在创建完<code>SmsAuthenticationFilter</code>后，我们需要创建一个支持处理该类型Token的类，即<code>SmsAuthenticationProvider</code>，该类需要实现<code>AuthenticationProvider</code>的两个抽象方法：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsAuthenticationProvider</span> <span class="keyword">implements</span> <span class="title">AuthenticationProvider</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> UserDetailService userDetailService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Authentication <span class="title">authenticate</span><span class="params">(Authentication authentication)</span> <span class="keyword">throws</span> AuthenticationException </span>&#123;</span><br><span class="line">        SmsAuthenticationToken authenticationToken = (SmsAuthenticationToken) authentication;</span><br><span class="line">        UserDetails userDetails = userDetailService.loadUserByUsername((String) authenticationToken.getPrincipal());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (userDetails == <span class="keyword">null</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> InternalAuthenticationServiceException(<span class="string">"未找到与该手机号对应的用户"</span>);</span><br><span class="line"></span><br><span class="line">        SmsAuthenticationToken authenticationResult = <span class="keyword">new</span> SmsAuthenticationToken(userDetails, userDetails.getAuthorities());</span><br><span class="line"></span><br><span class="line">        authenticationResult.setDetails(authenticationToken.getDetails());</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> authenticationResult;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">supports</span><span class="params">(Class&lt;?&gt; aClass)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> SmsAuthenticationToken.class.isAssignableFrom(aClass);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> UserDetailService <span class="title">getUserDetailService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> userDetailService;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setUserDetailService</span><span class="params">(UserDetailService userDetailService)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.userDetailService = userDetailService;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>其中<code>supports</code>方法指定了支持处理的Token类型为<code>SmsAuthenticationToken</code>，<code>authenticate</code>方法用于编写具体的身份认证逻辑。在<code>authenticate</code>方法中，我们从<code>SmsAuthenticationToken</code>中取出了手机号信息，并调用了<code>UserDetailService</code>的<code>loadUserByUsername</code>方法。该方法在用户名密码类型的认证中，主要逻辑是通过用户名查询用户信息，如果存在该用户并且密码一致则认证成功；而在短信验证码认证的过程中，该方法需要通过手机号去查询用户，如果存在该用户则认证通过。认证通过后接着调用<code>SmsAuthenticationToken</code>的<code>SmsAuthenticationToken(Object principal, Collection&lt;? extends GrantedAuthority&gt; authorities)</code>构造函数构造一个认证通过的Token，包含了用户信息和用户权限。</p><p>你可能会问，为什么这一步没有进行短信验证码的校验呢？实际上短信验证码的校验是在<code>SmsAuthenticationFilter</code>之前完成的，即只有当短信验证码正确以后才开始走认证的流程。所以接下来我们需要定一个过滤器来校验短信验证码的正确性。</p><h3 id="定义SmsCodeFilter"><a href="#定义SmsCodeFilter" class="headerlink" title="定义SmsCodeFilter"></a>定义SmsCodeFilter</h3><p>短信验证码的校验逻辑其实和图形验证码的校验逻辑基本一致，所以我们在图形验证码过滤器的基础上稍作修改，代码如下所示：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsCodeFilter</span> <span class="keyword">extends</span> <span class="title">OncePerRequestFilter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AuthenticationFailureHandler authenticationFailureHandler;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> SessionStrategy sessionStrategy = <span class="keyword">new</span> HttpSessionSessionStrategy();</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">doFilterInternal</span><span class="params">(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, </span></span></span><br><span class="line"><span class="function"><span class="params">    	FilterChain filterChain)</span> <span class="keyword">throws</span> ServletException, IOException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (StringUtils.equalsIgnoreCase(<span class="string">"/login/mobile"</span>, httpServletRequest.getRequestURI())</span><br><span class="line">                &amp;&amp; StringUtils.equalsIgnoreCase(httpServletRequest.getMethod(), <span class="string">"post"</span>)) &#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                validateCode(<span class="keyword">new</span> ServletWebRequest(httpServletRequest));</span><br><span class="line">            &#125; <span class="keyword">catch</span> (ValidateCodeException e) &#123;</span><br><span class="line">                authenticationFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        filterChain.doFilter(httpServletRequest, httpServletResponse);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">validateSmsCode</span><span class="params">(ServletWebRequest servletWebRequest)</span> <span class="keyword">throws</span> ServletRequestBindingException </span>&#123;</span><br><span class="line">        String smsCodeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), <span class="string">"smsCode"</span>);</span><br><span class="line">        String mobile = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), <span class="string">"mobile"</span>);</span><br><span class="line">        ValidateCode codeInSession = (ValidateCode) sessionStrategy.getAttribute(servletWebRequest, FebsConstant.SESSION_KEY_SMS_CODE + mobile);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (StringUtils.isBlank(smsCodeInRequest)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ValidateCodeException(<span class="string">"验证码不能为空！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (codeInSession == <span class="keyword">null</span>) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ValidateCodeException(<span class="string">"验证码不存在，请重新发送！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (codeInSession.isExpire()) &#123;</span><br><span class="line">            sessionStrategy.removeAttribute(servletWebRequest, FebsConstant.SESSION_KEY_SMS_CODE + mobile);</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ValidateCodeException(<span class="string">"验证码已过期，请重新发送！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (!StringUtils.equalsIgnoreCase(codeInSession.getCode(), smsCodeInRequest)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ValidateCodeException(<span class="string">"验证码不正确！"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        sessionStrategy.removeAttribute(servletWebRequest, FebsConstant.SESSION_KEY_SMS_CODE + mobile);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>方法的基本逻辑和之前定义的<code>ValidateCodeFilter</code>一致，这里不再赘述。</p><h3 id="配置生效"><a href="#配置生效" class="headerlink" title="配置生效"></a>配置生效</h3><p>在定义完所需的组件后，我们需要进行一些配置，将这些组件组合起来形成一个和上面流程图对应的流程。创建一个配置类<code>SmsAuthenticationConfig</code>：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SmsAuthenticationConfig</span> <span class="keyword">extends</span> <span class="title">SecurityConfigurerAdapter</span>&lt;<span class="title">DefaultSecurityFilterChain</span>, <span class="title">HttpSecurity</span>&gt; </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AuthenticationSuccessHandler authenticationSuccessHandler;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> AuthenticationFailureHandler authenticationFailureHandler;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> UserDetailService userDetailService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        SmsAuthenticationFilter smsAuthenticationFilter = <span class="keyword">new</span> SmsAuthenticationFilter();</span><br><span class="line">        smsAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));</span><br><span class="line">        smsAuthenticationFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);</span><br><span class="line">        smsAuthenticationFilter.setAuthenticationFailureHandler(authenticationFailureHandler);</span><br><span class="line">        </span><br><span class="line">        SmsAuthenticationProvider smsAuthenticationProvider = <span class="keyword">new</span> SmsAuthenticationProvider();</span><br><span class="line">        smsAuthenticationProvider.setUserDetailService(userDetailService);</span><br><span class="line"></span><br><span class="line">        http.authenticationProvider(smsAuthenticationProvider)</span><br><span class="line">                .addFilterAfter(smsAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>在流程中第一步需要配置<code>SmsAuthenticationFilter</code>，分别设置了<code>AuthenticationManager</code>、<code>AuthenticationSuccessHandler</code>和<code>AuthenticationFailureHandler</code>属性。这些属性都是来自<code>SmsAuthenticationFilter</code>继承的<code>AbstractAuthenticationProcessingFilter</code>类中。</p><p>第二步配置<code>SmsAuthenticationProvider</code>，这一步只需要将我们自个的<code>UserDetailService</code>注入进来即可。</p><p>最后调用<code>HttpSecurity</code>的<code>authenticationProvider</code>方法指定了<code>AuthenticationProvider</code>为<code>SmsAuthenticationProvider</code>，并将<code>SmsAuthenticationFilter</code>过滤器添加到了<code>UsernamePasswordAuthenticationFilter</code>后面。</p><p>到这里我们已经将短信验证码认证的各个组件组合起来了，最后一步需要做的是配置短信验证码校验过滤器，并且将短信验证码认证流程加入到Spring Security中。在<code>BrowserSecurityConfig</code>的<code>configure</code>方法中添加如下配置：</p><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BrowserSecurityConfig</span> <span class="keyword">extends</span> <span class="title">WebSecurityConfigurerAdapter</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MyAuthenticationSucessHandler authenticationSucessHandler;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MyAuthenticationFailureHandler authenticationFailureHandler;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> ValidateCodeFilter validateCodeFilter;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SmsCodeFilter smsCodeFilter;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> SmsAuthenticationConfig smsAuthenticationConfig;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> PasswordEncoder <span class="title">passwordEncoder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> BCryptPasswordEncoder();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">configure</span><span class="params">(HttpSecurity http)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class) <span class="comment">// 添加验证码校验过滤器</span></span><br><span class="line">            .addFilterBefore(smsCodeFilter, UsernamePasswordAuthenticationFilter.class) <span class="comment">// 添加短信验证码校验过滤器</span></span><br><span class="line">                .formLogin() <span class="comment">// 表单登录</span></span><br><span class="line">                    <span class="comment">// http.httpBasic() // HTTP Basic</span></span><br><span class="line">                    .loginPage(<span class="string">"/authentication/require"</span>) <span class="comment">// 登录跳转 URL</span></span><br><span class="line">                    .loginProcessingUrl(<span class="string">"/login"</span>) <span class="comment">// 处理表单登录 URL</span></span><br><span class="line">                    .successHandler(authenticationSucessHandler) <span class="comment">// 处理登录成功</span></span><br><span class="line">                    .failureHandler(authenticationFailureHandler) <span class="comment">// 处理登录失败</span></span><br><span class="line">                .and()</span><br><span class="line">                    .authorizeRequests() <span class="comment">// 授权配置</span></span><br><span class="line">                    .antMatchers(<span class="string">"/authentication/require"</span>,</span><br><span class="line">                            <span class="string">"/login.html"</span>,</span><br><span class="line">                            <span class="string">"/code/image"</span>,<span class="string">"/code/sms"</span>).permitAll() <span class="comment">// 无需认证的请求路径</span></span><br><span class="line">                    .anyRequest()  <span class="comment">// 所有请求</span></span><br><span class="line">                    .authenticated() <span class="comment">// 都需要认证</span></span><br><span class="line">                .and()</span><br><span class="line">                    .csrf().disable()</span><br><span class="line">                .apply(smsAuthenticationConfig); <span class="comment">// 将短信验证码认证配置加到 Spring Security 中</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p></p><p>具体含义见注释，这里不再赘述。</p><h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><p>重启项目，访问<a href="http://localhost:8080/login.html" target="_blank" rel="noopener">http://localhost:8080/login.html</a>，点击发送验证码，控制台输出如下：</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">您的登录验证码为：169638，有效时间为60秒</span><br></pre></td></tr></table></figure><p></p><p>输入该验证码，点击登录后页面如下所示：</p><p><img src="img/QQ截图20180731230532.png" alt="QQ截图20180731230532.png"></p><p>认证成功。</p><blockquote><p>源码链接 <a href="https://github.com/wuyouzhuguli/SpringAll/tree/master/38.Spring-Security-SmsCode" target="_blank" rel="noopener">https://github.com/wuyouzhuguli/SpringAll/tree/master/38.Spring-Security-SmsCode</a></p></blockquote><script>$(".post-body a").not(".thispage").addClass("ignore-href").attr("target","_blank")</script></div><div></div><div><div style="padding:10px 0;margin:20px auto;width:90%;text-align:center;color:#878787"><div>请作者喝瓶肥宅水~</div><button id="rewardButton" style="margin-top:10px" disable="enable" onclick='var e=document.getElementById("QR");"none"===e.style.display?e.style.display="block":e.style.display="none"'><span style="height:46px;width:46px;line-height:46px;border-radius:50%;color:#fe5f55;font-weight:600;background:#ffd5be;border:none;box-shadow:0 4px 8px 0 rgba(255,213,190,.4)">￥</span></button><div id="QR" style="display:none"><div id="wechat" style="display:inline-block"><img id="wechat_qr" src="/img/wechat_pay.png" alt="MrBird WeChat Pay"></div><div id="alipay" style="display:inline-block"><img id="alipay_qr" src="/img/ali_pay.png" alt="MrBird Alipay"></div></div></div><style>#QR img{width:auto;margin:.8em 1em 0 1em}</style></div><div><ul class="post-copyright"><li class="post-copyright-author"><strong>本文作者：</strong> MrBird</li><li class="post-copyright-link"><strong>本文链接：</strong> <a href="http://mrbird.cc/Spring-Security-SmsCode.html" title="Spring Security短信验证码登录">http://mrbird.cc/Spring-Security-SmsCode.html</a></li><li class="post-copyright-license"><strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li></ul></div><footer class="post-footer"><div class="post-tags" style="margin-bottom:1.3rem"><a href="/tags/Spring/" rel="tag"># Spring</a> <a href="/tags/Security/" rel="tag"># Security</a> <a href="/tags/Spring-Security/" rel="tag"># Spring Security</a></div><div class="post-nav"><div class="post-nav-next post-nav-item"><a href="/Spring-Security-RememberMe.html" rel="next" title="Spring Security添加记住我功能"><i class="fa fa-chevron-left"></i> Spring Security添加记住我功能</a></div><span class="post-nav-divider"></span><div class="post-nav-prev post-nav-item"><a href="/Spring-Security-Session-Manage.html" rel="prev" title="Spring Security Session管理">Spring Security Session管理 <i class="fa fa-chevron-right"></i></a></div></div></footer></article><hr><div id="container"></div><div class="post-spread"><div id="comment-div"></div><style>.valine .vlist{margin-bottom:3rem}.valine .vwrap .vcontrol .col.col-60{text-align:left}.valine .vlist .vcard .vhead,.valine .vlist .vcard section .vfooter{text-align:left}.valine .vlist .vcard section{padding-bottom:.5rem!important}.vname{color:#42b983!important}.valine .vinfo .col{text-align:left;margin-left:-27rem}div#comment-div{margin-bottom:-8rem}.valine .vlist .vcard .vcontent .code,.valine .vlist .vcard .vcontent code,.valine .vlist .vcard .vcontent pre{background:#fbfbfb}.valine .vlist .vcard .vcontent a{color:#42b983}.valine .vlist .vcard .vimg{border-radius:3px}.valine .vbtn{border-radius:2px;padding:.3rem 1.25rem}.valine .vbtn:active,.valine .vbtn:hover{color:#42b983;border-color:#42b983;background-color:#fff}.valine .vwrap .vheader .vinput:focus{border-bottom-color:#42b983}.valine .vlist .vcard .vcontent.expand:before{background:-webkit-gradient(linear,left top,left bottom,from(hsla(0,0%,100%,0)),to(hsla(0,0%,100%,.2)));background:linear-gradient(180deg,hsla(0,0%,100%,0),hsla(0,0%,100%,.2))}.valine .vlist .vcard .vcontent.expand:after{content:"点击展开";font-size:.4rem;text-align:right;left:-1rem;background:hsla(0,0%,100%,.2)}.valine .vlist .vcard section .vfooter .vat{color:#b3b3b3}.valine .vlist .vcard section .vfooter .vat:hover{color:#42b983}.vcontent img{margin:0}.valine .info{display:none}</style><script type="text/javascript" src="/js/av.min.js"></script><script type="text/javascript" src="/js/Valine.min.js"></script><script type="text/javascript" src="/js/activate-power-mode.js"></script><script>POWERMODE.colorful=!0,POWERMODE.shake=!1,document.body.addEventListener("input",POWERMODE),new Valine({el:"#comment-div",notify:!1,verify:!0,appId:"SMcDFP1bN1jgb9Lo8JmtICHm-gzGzoHsz",appKey:"dH4nrUrt3V5XiJiI6Qyejnbi",placeholder:"",path:window.location.pathname,avatar:"monsterid",guest_info:["nick","mail","link"]});var chicken='<a href="#"><img src="https://image.uisdc.com/wp-content/uploads/2018/06/uisdc-chat-chicken.gif" class="checken"></a>';$("#comment-div").prepend(chicken)</script></div></div><script>var $bqinline=$("img[alt='bq-inline']");$bqinline.css({width:"2.3rem",height:"2.3rem",display:"inline","vertical-align":"text-bottom"})</script></div><div class="comments" id="comments"></div></div><aside id="sidebar" class="sidebar" onselectstart="return!1"><div class="sidebar-inner"><ul class="sidebar-nav motion-element"><li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">Contents</li><li class="sidebar-nav-overview" data-target="site-overview">Site Preview</li></ul><section class="site-overview sidebar-panel"><div class="sidebar-sticky sticky"><div itemscope itemtype="http://schema.org/Person"><div class="author__avatar"><img src="/images/blogImage.jpg" class="author__avatar" alt="MrBird" itemprop="image"></div><div class="author__content"><h3 class="author__name" itemprop="name">MrBird's Blog</h3><p class="author__bio" itemprop="description">A simple blog, code repository, just keep blogging</p></div><div class="author__urls-wrapper"><button class="btn btn--inverse">Follow</button><ul class="author__urls social-icons"><li><a href="http://map.baidu.com/?newmap=1&s=s%26wd%3D%E7%A6%8F%E5%B7%9E%E5%B8%82%26c%3D300&from=alamap&tpl=mapcity" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-map-marker" aria-hidden="true"></i>&nbsp;&nbsp;FuZhou,CN</a></li><li><a href="https://love.mrbird.cc" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-diamond" aria-hidden="true"></i>&nbsp;&nbsp;Love</a></li><li><a href="https://cloud.mrbird.cn" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-chain" aria-hidden="true"></i>&nbsp;&nbsp;FEBS</a></li><li><a href="/atom.xml" target="_blank" itemprop="url" class="ignore-href"><i class="fa fa-fw fa-rss" aria-hidden="true"></i>&nbsp;&nbsp;RSS</a></li><li><a href="https://gitee.com/mrbirdd" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-codepen" aria-hidden="true"></i>&nbsp;&nbsp;Gitee</a></li><li><a href="https://github.com/wuyouzhuguli" target="_blank" itemprop="sameAs" class="ignore-href"><i class="fa fa-fw fa-github-alt" aria-hidden="true"></i>&nbsp;&nbsp;GitHub</a></li><li><a href="javascript:;" class="popup-trigger"><i class="fa fa-fw fa-search" aria-hidden="true"></i>&nbsp;&nbsp;Search</a></li></ul></div></div></div><script>var $urls=$(".author__urls").find("a");$urls.each(function(){var o=$(this);o.mouseenter(function(){o.css({color:"#414547"})}),o.mouseleave(function(){o.css({color:""})})})</script></section><section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active"><div class="post-toc"><div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#短信验证码生成"><span class="nav-number">1.</span> <span class="nav-text">短信验证码生成</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#改造登录页"><span class="nav-number">2.</span> <span class="nav-text">改造登录页</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#添加短信验证码认证"><span class="nav-number">3.</span> <span class="nav-text">添加短信验证码认证</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#定义SmsAuthenticationToken"><span class="nav-number">3.1.</span> <span class="nav-text">定义SmsAuthenticationToken</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义SmsAuthenticationFilter"><span class="nav-number">3.2.</span> <span class="nav-text">定义SmsAuthenticationFilter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义SmsAuthenticationProvider"><span class="nav-number">3.3.</span> <span class="nav-text">定义SmsAuthenticationProvider</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#定义SmsCodeFilter"><span class="nav-number">3.4.</span> <span class="nav-text">定义SmsCodeFilter</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置生效"><span class="nav-number">3.5.</span> <span class="nav-text">配置生效</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试"><span class="nav-number">4.</span> <span class="nav-text">测试</span></a></li></ol></div></div></section></div></aside></div></main><footer id="footer" class="footer" onselectstart="return!1"><div class="footer-inner"><div class="copyright">&copy; 2016 - <span itemprop="copyrightYear">2019</span>&nbsp;&nbsp; <span class="author" itemprop="copyrightHolder">MrBird</span>&nbsp;&nbsp;|<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>&nbsp;&nbsp;UV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_uv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span> &nbsp;&nbsp;PV&nbsp;<span class="busuanzi-value" id="busuanzi_value_site_pv" style="cursor:pointer" title="统计开始时间：2019年7月5日"></span></div></div></footer><div class="back-to-top"><span style="font-family:'Source Sans Pro','Helvetica Neue',Arial,sans-serif;font-size:1.2em;font-weight:600">TOP</span></div></div><script type="text/javascript">"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script><script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script><script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script><script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script><script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script><script type="text/javascript">function proceedsearch(){$("body").append('<div class="search-popup-overlay local-search-pop-overlay"></div>').css("overflow","hidden"),$(".search-popup-overlay").click(onPopupClose),$(".popup").toggle();var t=$("#local-search-input");t.attr("autocapitalize","none"),t.attr("autocorrect","off"),t.focus()}var isfetched=!1,isXml=!0,search_path="search.xml";0===search_path.length?search_path="search.xml":search_path.endsWith("json")&&(isXml=!1);var path="/"+search_path,onPopupClose=function(t){$(".popup").hide(),$("#local-search-input").val(""),$(".search-result-list").remove(),$("#no-result").remove(),$(".local-search-pop-overlay").remove(),$("body").css("overflow","")},searchFunc=function(t,e,o){"use strict";$("body").append('<div class="search-popup-overlay local-search-pop-overlay"><div id="search-loading-icon"><i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i></div></div>').css("overflow","hidden"),$("#search-loading-icon").css("margin","20% auto 0 auto").css("text-align","center"),$.ajax({url:t,dataType:isXml?"xml":"json",async:!0,success:function(t){isfetched=!0,$(".popup").detach().appendTo(".header-inner");var n=isXml?$("entry",t).map(function(){return{title:$("title",this).text(),content:$("content",this).text(),url:$("url",this).text()}}).get():t,r=document.getElementById(e),s=document.getElementById(o),a=function(){var t=r.value.trim().toLowerCase(),e=t.split(/[\s\-]+/);e.length>1&&e.push(t);var o=[];if(t.length>0&&n.forEach(function(n){function r(e,o,n,r){for(var s=r[r.length-1],a=s.position,i=s.word,l=[],h=0;a+i.length<=n&&0!=r.length;){i===t&&h++,l.push({position:a,length:i.length});var p=a+i.length;for(r.pop();0!=r.length&&(s=r[r.length-1],a=s.position,i=s.word,p>a);)r.pop()}return c+=h,{hits:l,start:o,end:n,searchTextCount:h}}function s(t,e){var o="",n=e.start;return e.hits.forEach(function(e){o+=t.substring(n,e.position);var r=e.position+e.length;o+='<b class="search-keyword">'+t.substring(e.position,r)+"</b>",n=r}),o+=t.substring(n,e.end)}var a=!1,i=0,c=0,l=n.title.trim(),h=l.toLowerCase(),p=n.content.trim().replace(/<[^>]+>/g,""),u=p.toLowerCase(),f=decodeURIComponent(n.url),d=[],g=[];if(""!=l&&(e.forEach(function(t){function e(t,e,o){var n=t.length;if(0===n)return[];var r=0,s=[],a=[];for(o||(e=e.toLowerCase(),t=t.toLowerCase());(s=e.indexOf(t,r))>-1;)a.push({position:s,word:t}),r=s+n;return a}d=d.concat(e(t,h,!1)),g=g.concat(e(t,u,!1))}),(d.length>0||g.length>0)&&(a=!0,i=d.length+g.length)),a){[d,g].forEach(function(t){t.sort(function(t,e){return e.position!==t.position?e.position-t.position:t.word.length-e.word.length})});var v=[];0!=d.length&&v.push(r(l,0,l.length,d));for(var C=[];0!=g.length;){var $=g[g.length-1],m=$.position,x=$.word,w=m-20,y=m+80;w<0&&(w=0),y<m+x.length&&(y=m+x.length),y>p.length&&(y=p.length),C.push(r(p,w,y,g))}C.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hits.length!==e.hits.length?e.hits.length-t.hits.length:t.start-e.start});var T=parseInt("1");T>=0&&(C=C.slice(0,T));var b="";b+=0!=v.length?"<li><a href='"+f+"' class='search-result-title'>"+s(l,v[0])+"</a>":"<li><a href='"+f+"' class='search-result-title'>"+l+"</a>",C.forEach(function(t){b+="<a href='"+f+'\'><p class="search-result">'+s(p,t)+"...</p></a>"}),b+="</li>",o.push({item:b,searchTextCount:c,hitCount:i,id:o.length})}}),1===e.length&&""===e[0])s.innerHTML='<div id="no-result"><i class="fa fa-search fa-5x" /></div>';else if(0===o.length)s.innerHTML='<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>';else{o.sort(function(t,e){return t.searchTextCount!==e.searchTextCount?e.searchTextCount-t.searchTextCount:t.hitCount!==e.hitCount?e.hitCount-t.hitCount:e.id-t.id});var a='<ul class="search-result-list">';o.forEach(function(t){a+=t.item}),a+="</ul>",s.innerHTML=a}};r.addEventListener("input",a),$(".local-search-pop-overlay").remove(),$("body").css("overflow",""),proceedsearch()}})};$(".popup-trigger").click(function(t){t.stopPropagation(),isfetched===!1?searchFunc(path,"local-search-input","local-search-result"):proceedsearch()}),$(".popup-btn-close").click(onPopupClose),$(".popup").click(function(t){t.stopPropagation()}),$(document).on("keyup",function(t){var e=27===t.which&&$(".search-popup").is(":visible");e&&onPopupClose()})</script></body><script>$(function(){$("a").not(".nav-link,.cloud-tie-join-count,.ignore-href,.jstree-anchor").addClass("animsition-link")});var burst1=new mojs.Burst({left:0,top:0,radius:{5:40},children:{shape:"circle",fill:["red","cyan","orange"],fillOpacity:.8,radiusX:3.5,radiusY:3.5}});document.addEventListener("click",function(a){null==a.target.href&&"footer"!=a.target.className&&"copyright"!=a.target.className&&"author__urls social-icons"!=a.target.className&&"author__avatar"!=a.target.className&&"sidebar sidebar-active"!=a.target.className&&burst1.tune({x:a.pageX,y:a.pageY}).generate().replay()})</script><script type="text/javascript" src="/js/message.js"></script></html><!-- rebuild by neat -->